package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {
    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 每分钟检查一次，如果订单状态为待支付，并且下单时间超过15分钟，则自动取消订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void cancelOrder() {
        log.info("取消超时订单{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        String status = String.valueOf(Orders.PENDING_PAYMENT);
        List<Orders> orders = ordersMapper.cancelOrder(status,time);
        if(orders != null && orders.size() > 0){
            for (Orders order : orders) {
                ordersMapper.updateStatus(order.getId(),Orders.CANCELLED,LocalDateTime.now(),"订单超时，已取消");
            }
        }
    }
    /**
     * 每天凌晨一点检查，如果状态为配送中，且在一小时前的订单则自动确认收货
     */
    @Scheduled(cron = "0 1 * * * *")
    public void confirmOrder() {
        log.info("确认收货{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusHours(-1);
        String status = String.valueOf(Orders.DELIVERY_IN_PROGRESS);
        List<Orders> orders = ordersMapper.cancelOrder(status,time);
        if(orders != null && orders.size() > 0){
            for (Orders order : orders) {
                Orders orders1 = new Orders();
                orders1.setId(order.getId());
                orders1.setStatus(Orders.COMPLETED);
                orders1.setDeliveryTime(LocalDateTime.now());
                ordersMapper.update(orders1);
            }
        }
    }
}
